package com.gongpingjialoan.activity.car;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseFragment;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.adapter.car.RecomendDiscountAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.car.LikeCarBean;
import com.gongpingjialoan.bean.car.RecomendCarBean;
import com.gongpingjialoan.data.CityData;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.view.LinearLayoutManager;
import com.google.gson.Gson;
import com.lsjwzh.widget.recyclerviewpager.RecyclerViewPager;

import java.util.ArrayList;
import java.util.List;

import static com.alibaba.sdk.android.feedback.impl.FeedbackAPI.mContext;
import static com.gongpingjialoan.R.id.error_id;
import static com.gongpingjialoan.R.id.iamge_all;

/**
 * Created by Administrator on 2015/12/11.
 */
public class RecomendDiscountFragment extends BaseFragment implements View.OnClickListener {

    private RecyclerViewPager mRecyclerViewPager;

    private final int REQUEST_CITY_FRAGMENT = 0X23;

    private View view;

    private List<RecomendCarBean> recomendCarBeans;

    private RecomendCarBean mfootCarBean = new RecomendCarBean();

    private LinearLayoutManager layout;

    private RecomendDiscountAdapter mRecomendDiscountAdapter;

    private NetDataJson netDataJson;

    private LikeCarBean likeCarBean;

    private Button againButton;

    private Handler mHandler;

    private static final int TIME_REMAIN = 0x00191;

    private TextView selectTextView, allTextView;

    private View selectLinearLayout;

    private boolean isNeedRefresh = false, isUpdate = false;

    private  boolean  isSeeAgain  =false;

    private int page = 1;

    private boolean isLoadingmore = false;

    private LinearLayout errorLinearLayout;

    private RelativeLayout loadingRelativeLayout;

    private TextView errorTextView;

    public String currentCity;

    private RecomendCarBean selectRecomendCarBean;

    private boolean isFilter = false;

    private static final int REQUEST_FILTER = 0x1234;

    private Bundle discountBundle;

    private String tags = "", car_age = "";

    private String pushed_car_id;

    private View leftImageView, rightImageView;

    private NetDataJson changeCityNetDataJson;

    public TextView tileTextView;
    private TextView scollTipTv;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        action = "recommend";
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.recommend_discount_layout, container, false);
        initView();
        initData();
        initHandler();
        return view;
    }


    @SuppressLint("HandlerLeak")
    private void initHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                countDown(1);
            }
        };
    }


    private void initData() {
        pushed_car_id = getActivity().getIntent().getStringExtra("pushed_car_id");
        currentCity = MainActivity.main.currentCity;
        if ("成都".equals(currentCity)) {
            tileTextView.setText("抢好车");
            if(mRecomendDiscountAdapter != null){
                mRecomendDiscountAdapter.setType("抢好车");
            }
        } else {
            tileTextView.setText("猜你喜欢");
            if(mRecomendDiscountAdapter != null){
                mRecomendDiscountAdapter.setType("猜你喜欢");
            }
        }

        isLoadingmore = true;
        errorLinearLayout.setVisibility(View.GONE);
        if (netDataJson == null) {
            netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    isSeeAgain = false;
                    loadingRelativeLayout.setVisibility(View.GONE);
                    if (recomendCarBeans.size() == 0) {
                        mRecyclerViewPager.setVisibility(View.GONE);
                        selectLinearLayout.setVisibility(View.GONE);
                        errorLinearLayout.setVisibility(View.VISIBLE);
                        errorTextView.setText("您的网络不稳定\n请重新加载");
                        againButton.setText("再来一次");
                        errorTextView.setTag("net");
                    }
                    Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                    isNeedRefresh = false;
                    isLoadingmore = false;
                }

                @Override
                public void onDataJsonUpdate(String json) {
                    Gson gson = new Gson();
                    try {
                        likeCarBean = gson.fromJson(json.toString(), LikeCarBean.class);
                    } catch (Exception exception) {
                        loadingRelativeLayout.setVisibility(View.GONE);
                        mRecyclerViewPager.setVisibility(View.GONE);
                        errorLinearLayout.setVisibility(View.VISIBLE);
                        errorTextView.setText("当前城市没有车源哦\n换个城市看看");
                        againButton.setText("换个城市看看");
                        errorTextView.setTag("no");
                        return;
                    }
                    if ("success".equals(likeCarBean.getStatus())) {
                        if (isNeedRefresh) {
                            selectTextView.setText("1");

                            recomendCarBeans.clear();
                            isNeedRefresh = false;
                            mRecyclerViewPager.scrollBy(5, 0);
                            if(isSeeAgain){
                                mRecyclerViewPager.scrollToPosition(0);
                                leftImageView.setVisibility(View.VISIBLE);
                            } else {
                                leftImageView.setVisibility(View.GONE);
                            }
//                            mRecomendDiscountAdapter.notifyDataSetChanged();
                        }

                        if (likeCarBean.getCars().size() == 0) {
                            loadingRelativeLayout.setVisibility(View.GONE);
                            if (recomendCarBeans.size() == 0) {
                                mRecyclerViewPager.setVisibility(View.GONE);
                            }
                            errorLinearLayout.setVisibility(View.VISIBLE);
                            if (isFilter) {
                                errorTextView.setText("您的条件太苛刻了\n试试别的搜索条件吧~");
                                againButton.setText("再来一次");
                                errorTextView.setTag("fliter");
                            } else {
                                errorTextView.setText("当前城市没有车源哦\n换个城市看看");
                                againButton.setText("换个城市看看");
                                errorTextView.setTag("no");
                            }
                            return;
                        }

                        recomendCarBeans.addAll(likeCarBean.getCars());
                        allTextView.setText("/" + likeCarBean.getCount());
                        mRecomendDiscountAdapter.setSize(recomendCarBeans.size());
                        //没有加载更多
                        if (likeCarBean.getTotal_page() <= page) {
                            recomendCarBeans.add(mfootCarBean);
                        }

                        mRecomendDiscountAdapter.notifyDataSetChanged();
                        if (isUpdate) {
                            isUpdate = false;
                            mRecyclerViewPager.scrollBy(5, 0);
                        }
                        mRecyclerViewPager.setVisibility(View.VISIBLE);
                        selectLinearLayout.setVisibility(View.VISIBLE);
                        isFilter = false;
                        if ("成都".equals(currentCity)) {
                            mHandler.removeMessages(TIME_REMAIN);
                            mHandler.sendEmptyMessageDelayed(TIME_REMAIN, 1000);
                        }
                    } else {
                        if (recomendCarBeans.size() == 0) {
                            mRecyclerViewPager.setVisibility(View.GONE);
                            selectLinearLayout.setVisibility(View.GONE);
                        }
                        Toast.makeText(getActivity(), likeCarBean.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                    loadingRelativeLayout.setVisibility(View.GONE);
                    isLoadingmore = false;
                    isSeeAgain = false;
                }
            }, 1);
        }
        netDataJson.setUrl(API.get_recomend_cars);
        netDataJson.clearMap();
        if (!TextUtils.isEmpty(tags))
            netDataJson.addParam("tags", tags);
        if (!TextUtils.isEmpty(car_age))
            netDataJson.addParam("car_age", car_age);
        netDataJson.addParam("city", currentCity);
        netDataJson.addParam("page", page);
        if (TextUtils.isEmpty(tags) && TextUtils.isEmpty(car_age))
            netDataJson.addParam("pushed_car_id", pushed_car_id);
        netDataJson.request("get");
        loadingRelativeLayout.setVisibility(View.VISIBLE);
    }


    private void initView() {
        leftImageView = view.findViewById(R.id.left);
        rightImageView = view.findViewById(R.id.right);
        leftImageView.setOnClickListener(this);
        rightImageView.setOnClickListener(this);
        tileTextView = (TextView) view.findViewById(R.id.top_title1);

        loadingRelativeLayout = (RelativeLayout) view.findViewById(R.id.main_loading);
        errorLinearLayout = (LinearLayout) view.findViewById(R.id.error_layout);
        errorTextView = (TextView) view.findViewById(error_id);
        againButton = (Button) view.findViewById(R.id.again_id);
        againButton.setOnClickListener(this);
        //加入底部
        mfootCarBean.setRecommend_type("foot");
        selectLinearLayout = view.findViewById(R.id.slect_layout);
        selectLinearLayout.setVisibility(View.GONE);
        selectTextView = (TextView) view.findViewById(R.id.iamge_select);
        scollTipTv = (TextView) view.findViewById(R.id.scoll_tip_tv);
        allTextView = (TextView) view.findViewById(iamge_all);
        recomendCarBeans = new ArrayList<>();
        mRecyclerViewPager = (RecyclerViewPager) view.findViewById(R.id.viewpager);
        layout = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL,
                false);
        mRecyclerViewPager.setLayoutManager(layout);
        mRecomendDiscountAdapter = new RecomendDiscountAdapter(recomendCarBeans, this);
        mRecyclerViewPager.setAdapter(mRecomendDiscountAdapter);
        mRecyclerViewPager.setHasFixedSize(true);
        mRecyclerViewPager.setLongClickable(true);
        mRecyclerViewPager.setVisibility(View.GONE);
        mRecyclerViewPager.setItemAnimator(new DefaultItemAnimator());
        mRecyclerViewPager.getItemAnimator().setSupportsChangeAnimations(false);
        mRecyclerViewPager.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int scrollState) {
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int i1, int i2) {
                int childCount = mRecyclerViewPager.getChildCount();
                if (childCount == 0) return;
                int width = mRecyclerViewPager.getChildAt(0).getWidth();
                int height = mRecyclerViewPager.getChildAt(0).getHeight();
                int padding = (mRecyclerViewPager.getWidth() - width) / 2;
                for (int j = 0; j < childCount; j++) {
                    View v = recyclerView.getChildAt(j);
                    if (v.getTag() != null) {
                        if ("foot".equals(v.getTag().toString())) {
                            break;
                        }
                    }
                    //往左 从 padding 到 -(v.getWidth()-padding) 的过程中，由大到小
                    float rate = 0;
                    if (v.getLeft() <= padding) {
                        if (v.getLeft() >= padding - v.getWidth()) {
                            rate = (padding - v.getLeft()) * 1f / v.getWidth();
                        } else {
                            rate = 1;
                        }
                        v.setScaleX(1 - rate * 0.1f);
                        v.setScaleY(1 - rate * 0.1f);
                        v.setPivotX(width * 0.5f);
                        v.setPivotY(height);
                        v.setRotation(-rate * 0.1f * 45);

                    } else {
                        //往右 从 padding 到 recyclerView.getWidth()-padding 的过程中，由大到小
                        if (v.getLeft() <= recyclerView.getWidth() - padding) {
                            rate = (recyclerView.getWidth() - padding - v.getLeft()) * 1f / v.getWidth();
                        }
                        v.setScaleX(0.9f + rate * 0.1f);
                        v.setScaleY(0.9f + rate * 0.1f);
                        v.setPivotX(width * 0.5f);
                        v.setPivotY(height);
                        v.setRotation((0.1f + rate * 0.1f) * 45);
                        //  v.setRotation(rate * 360);
                    }
                }
            }
        });
        mRecyclerViewPager.addOnPageChangedListener(new RecyclerViewPager.OnPageChangedListener() {
            @Override
            public void OnPageChanged(int oldPosition, int newPosition) {
                if (newPosition + 1 > roll_pages) {
                    roll_pages = newPosition + 1;
                }
                Utils.LogD("addOnPageChanged  "+"newPosition " +newPosition+"oldPosition " +oldPosition+"roll_pages " +roll_pages);
                Utils.LogD("addOnPageChanged  "+"recomendCarBeans.size() " +recomendCarBeans.size()+"likeCarBean.getTotal_page() " +likeCarBean.getTotal_page());
                if (newPosition < 0  ||newPosition >= recomendCarBeans.size())return;
                //滑动到最后一条
                if (newPosition == recomendCarBeans.size() - 1) {
                    if (isLoadingmore)
                        return;
                    //加载更多
                    if (likeCarBean.getTotal_page() > page) {
                        page++;
                        selectTextView.setText(newPosition + 1 + "");
                        scollTipTv.setVisibility(View.GONE);
                        initData();
                    } else {
//                        recomendCarBeans.clear();
                        leftImageView.setVisibility(View.VISIBLE);
                        rightImageView.setVisibility(View.GONE);
                        selectTextView.setVisibility(View.GONE);
                        scollTipTv.setVisibility(View.VISIBLE);
                        allTextView.setVisibility(View.GONE);
                        if (!recomendCarBeans.contains(mfootCarBean)) {
                            recomendCarBeans.add(mfootCarBean);
                            mRecomendDiscountAdapter.notifyDataSetChanged();
//                            selectLinearLayout.setVisibility(View.GONE);
                        }

                    }
                } else {
                    scollTipTv.setVisibility(View.GONE);
                    selectTextView.setText(newPosition + 1 + "");
                    allTextView.setVisibility(View.VISIBLE);
                    rightImageView.setVisibility(View.VISIBLE);
                    selectTextView.setVisibility(View.VISIBLE);
                    if (newPosition == 0) {
                        leftImageView.setVisibility(View.GONE);
                    } else {
                        leftImageView.setVisibility(View.VISIBLE);
                    }
                }
            }
        });


    }


    /**
     * 倒计时
     * down_time
     */
    private void countDown(long down_time) {
        int size = recomendCarBeans.size();
        for (int i = 0; i < size; i++) {
            RecomendCarBean recomendCarBean = recomendCarBeans.get(i);
            if ("promo_car".equals(recomendCarBean.getRecommend_type())) {
                long time = Long.parseLong(recomendCarBean.getD_remain_time()) - down_time;
                if (time >= 0) {
                    recomendCarBean.setD_remain_time(time + "");
                } else {
                    recomendCarBean.setD_remain_time(recomendCarBean.getPromo_total_seconds());
                }
            }
        }
        mRecomendDiscountAdapter.notifyItemChanged(mRecyclerViewPager.getCurrentPosition());
        mHandler.sendEmptyMessageDelayed(TIME_REMAIN, 1000);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mHandler != null) {
            mHandler.removeMessages(TIME_REMAIN);
        }
        if (netDataJson != null) {
            netDataJson.cancelTask();
            netDataJson = null;
        }

        if (changeCityNetDataJson != null) {
            changeCityNetDataJson.cancelTask();
            changeCityNetDataJson = null;
        }
    }


    public void gotoCheshi() {
        isSeeAgain = true;
        isNeedRefresh = true;
//        MainActivity.main.gotocheshi(false);
        page = 1;
        selectTextView.setText("1");
        initData();
        PointRecordManage.getInstance().addPoint(mContext,"GoodCarRecommendRefresh");
    }

    public void haoping() {
        isNeedRefresh = true;
        try {
            Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("market://details?id=com.gongpingjia"));
            viewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(viewIntent);
        } catch (Exception e) {
            Toast.makeText(getActivity(), "尚未安装应用市场", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden && isNeedRefresh) {
            page = 1;
            selectTextView.setText("1");
            initData();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (isNeedRefresh) {
            page = 1;
            selectTextView.setText("1");
            initData();
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_FILTER:
                    discountBundle = data.getExtras();
                    tags = discountBundle.getString("tags", "");
                    car_age = discountBundle.getString("car_age", "");
                    //刷新
                    isFilter = true;
                    updateDiscountListData();
                    break;
                case REQUEST_CITY_FRAGMENT:
                    Bundle b = data.getExtras();
                    String city = b.getString("city");
                    MainActivity.main.currentCity = city;
                    Utils.changeCity(city);
                    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user_city", Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString("city", city);
                    edit.commit();
                    CityData mCityData = GPJApplication.getInstance().getCityData();
                    mCityData.mCurrentCity = city;

                    GPJApplication.getInstance().isChangeCity = true;
                    if (MainActivity.main != null) {

                        if (MainActivity.main.assessmentFragment != null && MainActivity.main.assessmentFragment.isAdded()) {
                            MainActivity.main.assessmentFragment.changCity(city);
                        }
                        if (isAdded()) {
                            updateDiscountListData();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }


    public void updateDiscountListData() {
        //登入登出筛选时 如果不是特卖城市 不刷新   用于城市切换时刷新
        if (isAdded()) {
            page = 1;
            selectTextView.setText("1");
            mRecyclerViewPager.setVisibility(View.GONE);
            selectLinearLayout.setVisibility(View.GONE);
            isNeedRefresh = true;
            //recomendCarBeans.clear();
            //  mRecomendDiscountAdapter.notifyDataSetChanged();
            mRecyclerViewPager.scrollToPosition(0);
            mRecyclerViewPager.scrollBy(5, 0);
            selectRecomendCarBean = null;
            isUpdate = true;
            initData();
        }
    }

    public void updateDiscountListItem() {
        if (selectRecomendCarBean != null) {
            selectRecomendCarBean.setIs_appointed(true);
            int size = Integer.parseInt(selectRecomendCarBean.getAppoint_count()) + 1;
            selectRecomendCarBean.setAppoint_count(size + "");
            mRecomendDiscountAdapter.notifyDataSetChanged();
        }
    }

    public void setSelectRecomendCarBean(RecomendCarBean selectRecomendCarBean) {
        this.selectRecomendCarBean = selectRecomendCarBean;
    }

    @Override
    public void onClick(View v) {
        if (v == againButton) {
            if ("no".equals(errorTextView.getTag().toString())) {
                Intent cityit = new Intent();
                cityit.putExtra("needProvince", false);
                cityit.setClass(getActivity(), CityActivity.class);
                startActivityForResult(cityit, REQUEST_CITY_FRAGMENT);
            } else {
                page = 1;
                selectTextView.setText("1");
                selectLinearLayout.setVisibility(View.GONE);
                recomendCarBeans.clear();
                mRecomendDiscountAdapter.notifyDataSetChanged();
                mRecyclerViewPager.smoothScrollToPosition(0);
                initData();
            }
        } else if (v == leftImageView) {
            if (mRecyclerViewPager.getCurrentPosition() > 0) {
                mRecyclerViewPager.smoothScrollToPosition(mRecyclerViewPager.getCurrentPosition() - 1);
            }
        } else if (v == rightImageView) {
            if (mRecyclerViewPager.getCurrentPosition() < recomendCarBeans.size()) {
                mRecyclerViewPager.smoothScrollToPosition(mRecyclerViewPager.getCurrentPosition() + 1);
            }
        }
    }


}
